import { GameModel, TeamOrder, WayInfo } from "../../config/play_def"
import { CardSkill } from "../../config/role_def";
import { PlayGround_Listen, UI_Layer, UI_Listen } from "../../config/ui_def";
// import { BoidSkill } from "../../constants/boid_def";
import { Sdk_Platform, WX_AD_CONFIG, VIVO_AD_CONFIG } from '../../frame/constants';
cc.Class({
    extends: cc.Component,

    properties: {
        scale_node: [cc.Node],
        scale_widget: [cc.Widget],

        ready_node: cc.Node,        // 怪物初始节点 怪物会在此处排队
        way_node: cc.Node,          // 道路节点 前期有用后期无用
        effect_node: cc.Node,       // 特效节点 在怪物上 子弹下
        boids_node: cc.Node,        // 怪物节点
        bullet_node: cc.Node,       // 子弹节点
        top_effect_node: cc.Node,   // 顶级效果节点

        disk_spine: sp.Skeleton,    // disk

        tower_node: cc.Node,    // 炮塔节点
        loading: true,          // 初始状态
        checkGuide: false
    },
    initInfo() {
        this.loading = true
        this.checkGuide = false
        gg.eventManager.on('check', this.guideCheck, this)
        gg.eventManager.on('playground', this.listenClient, this)
        // 战斗区域适配调整
        for (let i = 0; i < this.scale_node.length; i++) {
            this.scale_node[i].scale = zoom_scale
        }
        // 长屏幕适配
        // if (he.func.getLongScreen()) {
        //     for (let i = 0; i < this.scale_widget.length; i++) {
        //         this.scale_widget[i].verticalCenter = 130
        //         this.scale_widget[i].updateAlignment()
        //     }
        // }
        this.isNew = he.local.getJson('isNew') || false
        let localtimeSave = he.local.getJson('localTimeSave')
        this.loginTime = localtimeSave.loginTime
        this.chayeTime = localtimeSave.chayeTime
        this.bannerTime = localtimeSave.bannerTime
        this.videoTime = localtimeSave.videoTime
        this.updateNativeTime = localtimeSave.updateNativeTime || 0
        this.canShowAd = false
        this.canShowChaye = false
        this.canShowBanner = false
        this.bindManager()
        this.initWayBox()       // 初始化格子
        // 炮塔绑定
        this.loadUserSpine()
        // 碰撞区域开启
        let collisionManager = cc.director.getCollisionManager();
        collisionManager.enabled = true;
        gg.uiManager.addPage(UI_Layer.Load, {
            name: "fightAdPage",
        })
        //collisionManager.enabledDebugDraw = true;
        // 之后放在加载部分
    },

    listenClient(code, param, arg) {
        if (parseInt(code.type)) {
            switch (parseInt(code.type)) {
                case UI_Listen.PLGD_STARTEND:
                    this.canShowAd = false
                    this.canShowChaye = true
                    this.canShowBanner = true
                    let guideList = he.local.getJson('guideList', 'user')
                    if (!guideList) {
                        return
                    } else {
                        if (!guideList[6]) {
                            //新手引导

                        } else {
                            switch (common.sdk_env) {
                                case Sdk_Platform.VIVO:
                                    gg.uiManager.addPage(UI_Layer.Cover, {
                                        name: "useSkillPage",
                                    })
                                    break
                                case Sdk_Platform.OPPO:
                                    break
                                case Sdk_Platform.WECHAT:
                                    gg.uiManager.addPage(UI_Layer.Cover, {
                                        name: "useSkillPage",
                                    })
                                    break
                                default:
                                    gg.uiManager.addPage(UI_Layer.Cover, {
                                        name: "useSkillPage",
                                    })
                                    break
                            }''
                        }
                    }

                    break

                case UI_Listen.PLGD_ENDAD:
                    this.canShowAd = true
                    this.pageName = 'GameOver'
                    break
                case UI_Listen.PLGD_VIDEO:
                    console.log('PLGD')
                    if (this.chayeTime >= 15) {
                        console.log('PLGD_gtime')
                        gg.uiManager.closePage(UI_Layer.Msg, 'chayeAdFake')
                        if (param) {
                            param()
                            this.chayeTime = 0
                            this.bannerTime = 0
                        }
                    }
                    break
            }
        }
    },


    // 加载spine
    loadUserSpine() {
        // 创建池子
        let loadPool = [
            { name: 'bullet', prefab: 'prefab/bullet' },
            { name: 'debullet', prefab: 'prefab/debullet' },
            { name: 'buffAni', prefab: 'prefab/buffAni' },
        ]
        // 加载其他资源
        let loadlist = []
        let team = gg.data.user_team
        for (let i = 0; i < team.length; i++) {
            if (!team[i].equips[team[i].hand]) {
                he.error("数据错误 该装备等级为0")
                continue
            }
            if (team[i].order <= 0) {
                he.log("队员未出列", team[i].order)
                continue
            }
            let info = he.db.getDataByArgs("Role", { roleId: team[i].id })
            let equip_info = he.db.getDataByArgs("Equip", { equip: team[i].hand, level: team[i].equips[team[i].hand] })
            loadlist.push({
                url: info.model, type: sp.SkeletonData, bundle: 'role'
            })
            loadlist.push({
                url: 'spine/bullet/' + equip_info.bulletModel, type: sp.SkeletonData,
            })
            loadlist.push({
                url: equip_info.bulletVoice, type: cc.AudioClip, bundle: 'voice'
            })
            loadlist.push({
                url: equip_info.attackVoice, type: cc.AudioClip, bundle: 'voice'
            })
        }
        let card_team = gg.data.card_team
        if (card_team.length) {
            loadlist.push(
                'page/SkillDebut'
            )
        }

        for (let i = 0; i < card_team.length; i++) {
            let card_info = he.db.getDataByArgs("Card", { cardId: card_team[i].id, level: card_team[i].lv })
            let card_param
            if (card_info.skillParam) {
                card_param = card_info.skillParam.split("/")
            }
            if (card_info.swapIn) {
                let swap_in_list = card_info.swapIn.split("#")
                for (let x = 0; x < swap_in_list.length; x++) {
                    let swap_item = swap_in_list[x].split("/")
                    if (swap_item[1]) {
                        let swap_role_info = he.db.getDataByArgs("Role", { roleId: parseInt(swap_item[1]), level: card_team[i].lv })
                        let swap_equip_info = he.db.getDataByArgs("Equip", { equip: parseInt(swap_item[0]), level: card_team[i].lv })
                        if (swap_role_info) {
                            loadlist.push({
                                url: swap_role_info.model, type: sp.SkeletonData, bundle: 'role'
                            })
                            if (swap_equip_info.bulletModel) {
                                loadlist.push({
                                    url: 'spine/bullet/' + swap_equip_info.bulletModel, type: sp.SkeletonData,
                                })
                            }
                            loadlist.push({
                                url: swap_equip_info.bulletVoice, type: cc.AudioClip, bundle: 'voice'
                            })
                            loadlist.push({
                                url: swap_equip_info.attackVoice, type: cc.AudioClip, bundle: 'voice'
                            })
                        }
                    }
                }
            }
            switch (card_info.skill) {
                case CardSkill.CreateBullet:
                    loadlist.push({
                        url: 'spine/bullet/' + card_param[1], type: sp.SkeletonData,
                    })
                    break
                case CardSkill.CreateDelayBullet:
                case CardSkill.CreateDecorate:
                    loadlist.push({
                        url: 'spine/bullet/' + card_param[3], type: sp.SkeletonData,
                    })
                    break
            }
        }
        let loadMonsters = []
        switch (gg.data.model) {
            case GameModel.ClearPass:
                for (let i = 0; i < gg.data.pass_list.length; i++) {
                    let teamMenber = gg.data.pass_list[i].teamMenber
                    if (teamMenber) {
                        teamMenber = teamMenber.split("#")
                        for (let j = 0; j < teamMenber.length; j++) {
                            if (loadMonsters.indexOf(teamMenber[j]) < 0) {
                                loadMonsters.push(teamMenber[j])
                            }
                        }
                    }
                }
                break
        }
        // 加载怪物
        if (loadMonsters.length) {
            for (let i = 0; i < loadMonsters.length; i++) {
                let info = he.db.getData("Monster", loadMonsters[i])
                if (info.model) {
                    loadlist.push({
                        url: info.model, type: sp.SkeletonData, bundle: 'monster'
                    })
                }
                if (info.bulletModel) {
                    loadlist.push({
                        url: 'spine/bullet/' + info.bulletModel, type: sp.SkeletonData,
                    })
                }
            }
        }
        // 创建池子
        for (let i = 0; i < loadPool.length; i++) {
            if (!he.pool.getPool(loadPool[i].name)) {
                he.pool.createPool(loadPool[i].name, 3, cc.Prefab, loadPool[i].prefab)
            }
            gg.uiManager.pool_list.push(loadPool[i])
        }
        // 开始按钮 后期改为引导按钮
        gg.uiManager.addPage(UI_Layer.Cover, {
            name: 'StartGuide',
            cover: true,
        })
        // this.showAd(false)
        this.canShowChaye = false
        this.canShowBanner = true
        this.canShowAd = true
        this.pageName = 'startGuide'
        this.loadlist = loadlist
        he.load.loadResList(loadlist, this.checkLoadover.bind(this))//将上面的list内的资源强制加载，然后触发回调函数checkLoadover
    },
    // 加载完成
    checkLoadover() {
        if (he.load.checkLoadOver(this.loadlist)) {
            he.log("加载结束 暂时没有填加载关闭动画")
            this.loading = false
            this.initRole()
            // this.guideCheck()
            gg.eventManager.emit('topInfo', PlayGround_Listen.UPDATE_HP)

        }
    },

    guideCheck() {
        if (!common.comicGuide) {
            return
        }
        let guideList = he.local.getJson('guideList', 'user')
        if (!guideList) {
            return
        } else {
            if (!guideList[5]) {
                //新手引导
                this.checkGuide = true
            }
        }
    },


    // 绑定场景节点
    bindManager() {
        // 怪物单位管理
        gg.boidsManager = this.node.getComponent('boidsManager')
        if (!gg.boidsManager) {
            gg.boidsManager = this.node.addComponent('boidsManager')
        }
        gg.boidsManager.enter_node = this.ready_node
        gg.boidsManager.way_node = this.way_node
        gg.boidsManager.ground_node = this.boids_node
        gg.boidsManager.initInfo()//调用对象池
        // 子弹脚本绑定
        gg.bulletManager = this.node.getComponent('bulletManager')
        if (!gg.bulletManager) {
            gg.bulletManager = this.node.addComponent('bulletManager')
        }
        gg.bulletManager.bullet_layer = this.bullet_node
        gg.bulletManager.effect_layer = this.effect_node
        gg.bulletManager.topeffect_layer = this.top_effect_node

        // 控制台管理
        gg.control = this.node.getComponent('controlManager')
        if (!gg.control) {
            gg.control = this.node.addComponent('controlManager')
        }
        gg.control.initInfo()
        // 
        this.bullet_node.on(cc.Node.EventType.TOUCH_START, gg.control.turnAttack, gg.control)
        this.bullet_node.on(cc.Node.EventType.TOUCH_MOVE, gg.control.turnAttack, gg.control)
        this.bullet_node.on(cc.Node.EventType.TOUCH_END, gg.control.stopAttack, gg.control)
        this.bullet_node.on(cc.Node.EventType.TOUCH_CANCEL, gg.control.stopAttack, gg.control)
    },
    // 删除监听
    onDestroy() {
        this.bullet_node.off(cc.Node.EventType.TOUCH_START, gg.control.turnAttack, gg.control)
        this.bullet_node.off(cc.Node.EventType.TOUCH_MOVE, gg.control.turnAttack, gg.control)
        this.bullet_node.off(cc.Node.EventType.TOUCH_END, gg.control.stopAttack, gg.control)
        this.bullet_node.off(cc.Node.EventType.TOUCH_CANCEL, gg.control.stopAttack, gg.control)
        gg.eventManager.off('check', this.guideCheck, this)
        gg.eventManager.off('playground', () => {
            this.canShowAd = true
        }, this)
        he.voice.stopMusic()
        let localTimeSave = { loginTime: this.loginTime, chayeTime: this.chayeTime, bannerTime: this.bannerTime, videoTime: this.videoTime }
        he.local.setJson('localTimeSave', localTimeSave)
    },
    // 初始化格子
    initWayBox() {
        let wayUnit = cc.instantiate(he.load.get("prefab/wayUnit"))
        gg.boidsManager.way_size = wayUnit.getContentSize()
        gg.boidsManager.way_node = this.way_node
        wayUnit.destroy()
    },
    // 初始化炮塔角色
    initRole() {
        let tower_prefab = he.load.get('prefab/towerBase')
        for (let i = 0; i < WayInfo.col; i++) {
            let tower_node = cc.instantiate(tower_prefab)
            tower_node.x = gg.boidsManager.getXOffset(i)
            gg.control.roleScript[i + 1] = tower_node.getComponent("towerBase")
            gg.control.roleScript[i + 1].initInfo(i + 1)
            this.tower_node.addChild(tower_node)
            let fin_pos = gg.control.roleScript[i + 1].getWorldPos()
            fin_pos.y += this.tower_node.height / 2 - 50
            gg.control.wall_pos[i + 1] = fin_pos
            tower_node.zIndex = 5 - TeamOrder.indexOf(i + 1)
        }
        gg.control.roleInit()
        gg.control.disk_spine = this.disk_spine
        gg.control.diskAniListen()
        gg.uiManager.addPage(UI_Layer.Base, { name: 'TopInfo' })
        gg.uiManager.addPage(UI_Layer.Base, { name: 'SkillBox' })
        this.adSwitch(true)
    },
    adSwitch(status) {
        if (status) {
            switch (common.sdk_env) {
                case Sdk_Platform.WECHAT:
                    if (!common.showAd) return
                    gg.uiManager.addPage(UI_Layer.Base, {
                        name: "adIconPage",
                    })
                    break
            }
        } else {
            //  关掉广告
        }
    },
    //startguide检测一次是否打开banner
    showAd(canShowChaye) {
        switch (common.sdk_env) {
            case Sdk_Platform.VIVO:
                if (this.loginTime >= 10 && !this.isNew && this.chayeTime >= 30 && this.bannerTime >= 10 && canShowChaye) {
                    //生成插页广告
                    he.log('生成插页')
                    this.chayeTime = 0
                    this.bannerTime = 0
                    gg.uiManager.addPage(UI_Layer.Msg, {
                        name: 'chayeAdFake',
                        isShowAd: true,
                        isShowBanner: false
                    })
                }

                if (this.loginTime >= 10 && !this.isNew && this.chayeTime < 30 && this.bannerTime >= 10 && !canShowChaye) {
                    this.bannerTime = 0
                    gg.uiManager.addPage(UI_Layer.Msg, {
                        name: 'chayeAdFake',
                        isShowAd: true,
                        isShowBanner: true
                    })
                }
                break
        }
    },

    update(dt) {
        if (!this.loading) {
            if (!gg.data.pause && gg.data.status) {
                gg.data.updateWait(dt)
                gg.boidsManager.checkMonsterWait(dt)   // 怪物管理
                gg.control.checkBuff(dt)
                gg.control.checkHp(dt)
            }
        }
        if (this.checkGuide) {
            //检查技能新手引导
            if (gg.data.gameTime >= 3.1) {
                gg.data.pause = true
                this.checkGuide = false
                gg.eventManager.emit('newGuide', { index: 5 })
            }
        }
        if (this.chayeTime < 15 && this.canShowAd) {
            this.chayeTime += dt
        }
        //10秒间隔时间为能生成插页和banner的时间，若插页还在cd则生成banner
        if (this.bannerTime < 10 && this.canShowAd) {
            this.bannerTime += dt
        }
        //播放视频的间隔时间60s
        if (this.videoTime < 30 && this.canShowAd) {
            this.videoTime += dt
        }
        //初次进入游戏60秒内不得弹出任何广告
        if (this.loginTime < 30 && this.canShowAd) {
            this.loginTime += dt
        }
        if (this.updateNativeTime < 15 && this.canShowAd) {
            this.updateNativeTime += dt
        }
        switch (common.sdk_env) {
            case Sdk_Platform.VIVO:
                if (this.canShowAd && this.loginTime >= 10 && !this.isNew && this.chayeTime >= 10 && this.canShowChaye) {
                    //生成插页广告
                    // console.log('生成插页')
                    this.canShowAd = false
                    this.chayeTime = 0
                    this.bannerTime -= 5
                    gg.uiManager.addPage(UI_Layer.Msg, {
                        name: 'chayeAdFake',
                        isShowAd: true,
                        isShowBanner: false,
                        pageName: this.pageName,
                    })
                }

                if (this.canShowAd && this.loginTime >= 10 && !this.isNew && this.bannerTime >= 10 && this.canShowBanner) {
                    this.bannerTime = 0
                    this.canShowAd = false
                    gg.uiManager.addPage(UI_Layer.Msg, {
                        name: 'chayeAdFake',
                        isShowAd: true,
                        isShowBanner: true,
                        pageName: this.pageName,
                    })
                }

                // if (this.updateNativeTime >= 15) {
                //     he.ad.loadNativeAd(VIVO_AD_CONFIG.nativeAd[0])
                //     this.updateNativeTime = 0
                // }

                break
        }

    }


});
